package com.ytktt.study.week11.task8;

import com.ytktt.study.week11.task8.utils.UuidGenerator;
import io.lettuce.core.RedisClient;
import io.lettuce.core.ScriptOutputType;
import io.lettuce.core.SetArgs;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;

/**
 * TODO
 *
 * @author ytk
 */
public class GetLockApplication {

    private static final String UNLOCK_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

    public static void main(String[] args) throws InterruptedException {
        RedisClient redisClient = RedisClient.create("redis://localhost:6379/0");
        StatefulRedisConnection<String, String> connection = redisClient.connect();
        RedisCommands<String, String> syncCommands = connection.sync();
        String appId = UuidGenerator.getUuidWithoutHyphen();

        String lockResult = syncCommands.set("lock", appId, SetArgs.Builder.nx().ex(20));
        if ("OK".equals(lockResult)) {
            System.out.println(appId + "lock success");
            Thread.sleep(12000);
            syncCommands.eval(UNLOCK_SCRIPT, ScriptOutputType.INTEGER, new String[]{"lock"}, appId);
            System.out.println(appId + "unlock");
        }

        connection.close();
        redisClient.shutdown();
    }
}
